<template>
  <BasicDrawer v-bind="$attrs" @register="registerDrawer" :title="state.title" :width="width" @ok="handleSubmit" destroyOnClose>
    <BasicTable ref="tableRef" v-bind="getBindValue" :rowSelection="rowSelection" :rowKey="state.valueField">
      <template #tableTitle>
        <a-button preIcon="ant-design:plus-outlined" type="primary" @click="handleAdd">新增</a-button>
        <a-dropdown v-if="checkedKeys.length > 0 && state.batchDeleteApi">
          <template #overlay>
            <a-menu>
              <a-menu-item key="1" @click="batchHandleDelete">
                <Icon icon="ant-design:delete-outlined"></Icon>
                删除
              </a-menu-item>
            </a-menu>
          </template>
          <a-button>批量操作
            <Icon style="fontSize:12px" icon="ant-design:down-outlined"></Icon>
          </a-button>
        </a-dropdown>
      </template>
      <template #action="{ record }">
        <TableAction :actions="getActions(record)" />
      </template>
    </BasicTable>
  </BasicDrawer>
  <DataGroupModal @register="registerDataGroupModal" @success="tableRef.reload()"/>
</template>
<script lang="ts" setup>
import {nextTick, ref, unref, useAttrs, watch} from 'vue';
import {BasicDrawer, useDrawerInner} from '/@/components/Drawer';
import {useModal} from '/@/components/Modal';
import {useGlobSetting} from '/@/hooks/setting';
import {columns, searchFormSchema} from './dataGroup.data';
import {pageDataGroup} from '/@/api/infra/dataGroup'
import {useMessage} from '/@/hooks/web/useMessage';
import {isFunction} from '/@/utils/is';
import DataGroupModal from './DataGroupModal.vue';
import {createAsyncComponent} from '/@/utils/factory/createAsyncComponent';
import {useSelectBiz} from '/@/components/Form/src/jeecg/hooks/useSelectBiz';
import {Icon} from '/@/components/Icon';
//此处需要异步加载BasicTable
const BasicTable = createAsyncComponent(() => import('/@/components/Table/src/BasicTable.vue'), {
  loading: true,
})

const TableAction = createAsyncComponent(() => import('/@/components/Table/src/components/TableAction.vue'), {
  loading: true,
})

// 声明Emits
const emit = defineEmits(['success', 'register', 'getSelectResult']);
const attrs = useAttrs()

interface State {
  title?: string;
  /**
   * 业务类型
   * @see DataGroupBizType
   */
  bizType: string | number;
  /**
   * 组类型, 根据每个业务自行定义
   */
  groupType?: string;
  // 是否为树形结构, 编辑的时候会展示树
  isTree: boolean;
  //api
  deleteApi: Function;
  batchDeleteApi: Function;
  saveOrUpdateApi: Function;

  labelField: string,
  valueField: string,
  maxSelectCount: number,
  rowType: string
}

const state = ref<State>({
  title: '数据分组',
  isTree: false,
  labelField: 'label',
  valueField: 'id',
  bizType: '',
  maxSelectCount: -1,
  deleteApi: () => {},
  batchDeleteApi: () => {},
  saveOrUpdateApi: () => {},
  rowType: 'radio'
})
const tableRef = ref<any>()
const width = ref('800')

const { createMessage } = useMessage();
const glob = useGlobSetting();
const [registerDataGroupModal, { openModal: openDataGroupModal }] = useModal();

const config = {
  rowKey: 'id',
  api: pageDataGroup,
  beforeFetch: (params) => {
    params.bizType = state.value.bizType
  },
  showTableSetting: false,
  showIndexColumn: false,
  bordered: false,
  striped: false,
  immediate: false,
  columns: columns,
  formConfig: {
    schemas: searchFormSchema,
    showResetButton: false,
    fieldMapToTime: [['fieldTime', ['beginDate', 'endDate'], 'YYYY-MM-DD HH:mm:ss']],
  },
}

const getBindValue = Object.assign({}, unref(attrs), config);

const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
  state.value = Object.assign({...data}, unref(attrs))
  state.value.maxSelectCount = Number(state.value.maxSelectCount || -1)
  width.value = data.width || width.value


  setDrawerProps({ confirmLoading: false });
});

watch(
  () => tableRef.value,
  (val: any) => {
    tableRef.value && nextTick(() => tableRef.value.reload())
  }
);

const getIsRadioSelection = () => {
  const maxSelectCount = Number(unref(attrs)?.maxSelectCount || -1)
  return maxSelectCount !==  -1 && maxSelectCount  === 1 ? true : false
}
async function handleSubmit() {
  try {
    getSelectResult((options, values) => {
      //回传选项和已选择的值
      emit('getSelectResult',  options, unref(values));
      emit('success');
      //关闭弹窗
      closeDrawer();
    });
   
  } finally {
    setDrawerProps({ confirmLoading: false });
  }
}

const [{ rowSelection, checkedKeys, getSelectResult, selectRows }] = useSelectBiz(
  pageDataGroup,
  {
    ...getBindValue, 
    isRadioSelection: getIsRadioSelection(),
    params: { bizType: getBindValue.bizType }
  }
);

/**
* 新增事件
*/
function handleAdd() {
  openDataGroupModal(true, { 
    isUpdate: false, ...state.value
  });
}

/**
 * 删除事件
 */
async function handleDelete(record) {
  console.log('delete record', record);
  
  if (isFunction(state.value.deleteApi)) {
    await state.value.deleteApi({ id: record.id, name: record.name }, () => {
      tableRef.value.reload()
      createMessage.success('删除成功')
    });
    return
  } 
  console.error('state.deleteApi is not function');
  
}

/**
 * 批量删除事件
 */
async function batchHandleDelete() {
  console.log('batch selectRows', selectRows.value);
  
  if (isFunction(state.value.batchDeleteApi)) {
    await state.value.batchDeleteApi({ ids: selectRows.value.map(e => e['id']) }, () => {
      tableRef.value.reload()
      createMessage.success('删除成功')
    });
    return
  }
  console.error('state.batchDeleteApi is not function');
}

const handleEdit = (record) => {
  openDataGroupModal(true, { 
    isUpdate: true, 
    record,
    ...state.value
  });
}

/**
 * 操作列定义
 * @param record
 */
function getActions(record) {
  return [
    {
      label: '删除',
      ifShow: state.value.deleteApi !== undefined,
      popConfirm: {
        title: '是否确认删除',
        confirm: handleDelete.bind(null, record),
      },
    },
    {
      label: '编辑',
      onClick: handleEdit.bind(null, record),
      // ifShow: record.sendStatus == 0
    }
  ]
}
</script>
